package com.ble;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.ble.adapter.QuickAdapter;
import com.ble.utlis.PreferenceUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private QuickAdapter adapter;
    String TAG = "TAG";
    private Button btn_scan;
    private String mac = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.lv);
        btn_scan = findViewById(R.id.btn_scan);
        btn_scan.setOnClickListener(view -> {
            String text = btn_scan.getText().toString();
            if (text.equals("扫描")) {
                adapter.setNewData(new ArrayList<SearchResult>());
                initBle();
            } else {
                App.getBle().stopSearch();
            }
        });

        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        adapter = new QuickAdapter();

        //给RecyclerView设置适配器
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            SearchResult o = (SearchResult) adapter.getData().get(position);
            App.getBle().stopSearch();
            dismisspg();
            Intent intent2 = new Intent(MainActivity.this, BleDetailActivity.class);
            intent2.putExtra("NAME", o.getName());
            intent2.putExtra("MAC", o.getAddress());
            startActivityForResult(intent2, 0);
        });

        ble();

        mac = PreferenceUtil.getInstance(this).getMac("");
        if (!mac.isEmpty()) {
            showpg("正在连接设备");
        }
    }

    private void ble() {
        boolean bluetoothOpened = App.getBle().isBluetoothOpened();
        Log.e(TAG, "initView: bluetoothOpened" + bluetoothOpened);
        if (!bluetoothOpened) {
            App.getBle().openBluetooth();
            App.getBle().registerBluetoothStateListener(mBluetoothStateListener);
        } else {
            boolean b = requestPermission();
            if (b) {
                initBle();
            }
        }
    }

    private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            if (openOrClosed) {
                boolean b = requestPermission();
                if (b) {
                    initBle();
                }
            } else {

            }
        }

    };

    int REQUEST_PERMISSION_ACCESS_LOCATION = 1;

    private boolean requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_PERMISSION_ACCESS_LOCATION);

                Log.e(TAG, "requestPermission: ");
                return false;
            }

        }
        //做下面该做的事
        return true;
    }

    boolean connfalg = true;

    private void initBle() {
        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(10000, 2)
                .build();

        App.getBle().search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {
                btn_scan.setText("正在扫描...");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                Beacon beacon = new Beacon(device.scanRecord);
             //   Log.e(TAG, "onDeviceFounded: " + beacon.toString());

                List<SearchResult> data = adapter.getData();
                if (device.rssi == 0) {
                    return;
                }
                if (!data.contains(device)) {
                    adapter.addData(device);
                    App.getBle().registerConnectStatusListener(device.getAddress(), bleConnectStatusListener);

                }

                if (mac.equals(device.getAddress()) && connfalg) {
                    connfalg = false;
                    Intent intent2 = new Intent(MainActivity.this, BleDetailActivity.class);
                    intent2.putExtra("NAME", device.getName());
                    intent2.putExtra("MAC", device.getAddress());
                    startActivityForResult(intent2, 0);

                    App.getBle().stopSearch();
                    dismisspg();
                }
            }

            @Override
            public void onSearchStopped() {
                btn_scan.setText("扫描");
            }

            @Override
            public void onSearchCanceled() {
                btn_scan.setText("扫描");
            }
        });
    }

    BleConnectStatusListener bleConnectStatusListener = new BleConnectStatusListener() {
        @Override
        public void onConnectStatusChanged(String mac, int status) {
            Log.e(TAG, "onConnectStatusChanged: " + mac + "--------" + status);
            if (status == Constants.STATUS_CONNECTED) {

            } else if (status == Constants.STATUS_DISCONNECTED) {
                adapter.notifyDataSetChanged();
            }
        }
    };


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initBle();
                } else {
                    Toast.makeText(this, "获取权限失败", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private ProgressDialog progressDialog;

    private void showpg(String title) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage(title);
            progressDialog.show();

        } else {
            progressDialog.setTitle(title);
        }
    }

    private void dismisspg() {
        if (progressDialog != null) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }
}
